package com.xinxin.facelinker.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.easemob.chatuidemo.R;

import java.util.ArrayList;

/**
 * Created by gengliang on 2015/8/27.
 */
public class MotionImageAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Uri> datas;
    private GridView gv;

    public MotionImageAdapter(Context context, ArrayList<Uri> datas, GridView gv) {
        this.context = context;
        this.datas = datas;
        this.gv = gv;
    }

    @Override
    public int getCount() {
        return datas.size() > 0 ? datas.size() + 1 : 0;
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final RelativeLayout relativeLayout;

        if (convertView != null) {
            relativeLayout = (RelativeLayout) convertView;
        } else {
            relativeLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.layout_gridview_motion_photo, null);
        }

        int horizontalSpacing = gv.getHorizontalSpacing();
        int width = (gv.getWidth() - horizontalSpacing * 2
                - gv.getPaddingLeft() - gv.getPaddingRight()) / 3;

        ImageView ivMotionPhotoImage= (ImageView) relativeLayout.findViewById(R.id.ivMotionPhotoImage);
        ImageView ivMotionPhotoImageDelete= (ImageView) relativeLayout.findViewById(R.id.ivMotionPhotoImageDelete);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, width);
        ivMotionPhotoImage.setLayoutParams(params);

        if(position < getCount() - 1) {
            // set data
            Uri item =datas.get(position);
            ivMotionPhotoImage.setImageURI(item);

            ivMotionPhotoImageDelete.setVisibility(View.VISIBLE);
            ivMotionPhotoImageDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    datas.remove(position);
                    notifyDataSetChanged();
                }
            });
        } else {
            ivMotionPhotoImage.setImageResource(R.drawable.compose_pic_add);
            ivMotionPhotoImageDelete.setVisibility(View.GONE);
        }

        return relativeLayout;
    }
}
